package com.woniuxy.three.pms.shiro;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.three.pms.bean.UserBean;
import com.woniuxy.three.pms.root.service.IRootService;
import com.woniuxy.three.pms.user.service.IUserService;
import com.woniuxy.three.pms.util.CacheUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm{

	@Autowired
	private IUserService service;

	@Autowired
	private CacheUtil cacheUtil;

	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// 1. 从 PrincipalCollection 中来获取登录用户的信息
		System.out.println("============进入授权====————————=====================");
		Object principal = principals.getPrimaryPrincipal();
		// 2. 利用登录的用户的用户的信息来用户当前的角色或者授权（可能需要查询数据库）
		/**
		 * 假装有一个  角色
		 */
		Set<String> roles = new HashSet<>();
		roles.add("user");
		// 3. 创建 SimpleAuthorizationInfo ，并设置 roles属性
		System.out.println("=========================开始授权...============================");
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(roles);
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("执行User认证流程");
		// 1、将 AuthenticationToken 对象转化为 UsernamePasswordToken
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;

		// 2、获取到用户电话号码
		String mobile = upToken.getUsername();

		// 3、获取到数据库的信息
		UserBean dbUserInfo = service.findUserByMobile(mobile);

		// 4、将查询到的用户信息存入Redis，设置定期
		if (upToken.getPassword().length!=4){
			try {
				String dbValue = new ObjectMapper().writeValueAsString(dbUserInfo);
				cacheUtil.cacheWithKeyValue("login_info_"+mobile,dbValue);
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		}

		// 5、创建盐值
		ByteSource mobileSalt = ByteSource.Util.bytes(mobile);

		// 6、创建 AuthenticationInfo 对象
		AuthenticationInfo info = new SimpleAuthenticationInfo(dbUserInfo,dbUserInfo.getPassword(),mobileSalt,getName());

		return info;
	}
		
}
